package com.myh.gulimall.member.service.impl;

import com.myh.gulimall.member.dao.MemberLevelDao;
import com.myh.gulimall.member.entity.MemberLevelEntity;
import com.myh.gulimall.member.exception.PhoneExistException;
import com.myh.gulimall.member.exception.UserNameExistException;
import com.myh.gulimall.member.to.MemberRegistTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myh.common.utils.PageUtils;
import com.myh.common.utils.Query;

import com.myh.gulimall.member.dao.MemberDao;
import com.myh.gulimall.member.entity.MemberEntity;
import com.myh.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistTo memberRegistTo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        checkPhoneUnique(memberRegistTo.getPhone());
        checkUserNameUnique(memberRegistTo.getUserName());

        memberEntity.setMobile(memberRegistTo.getPhone());
        memberEntity.setUsername(memberRegistTo.getUserName());
        memberEntity.setPassword(memberRegistTo.getPassword());
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        Integer username = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

}